//
//  ZNWBMainController.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/7/28.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZNWBMainController: UITabBarController {
    
    private lazy var composeButton: UIButton = {
        let result = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button") ?? UIButton()
        result.addTarget(self, action: #selector(startComposing), for: .touchUpInside)
        
        return result
    }()
    
    //FIXME: - 未完成
    /// @objc privat保证方法的隐藏同时允许使用OC运行时消息机制被发现调用
    @objc private func startComposing() {
        // 1. 判断是否登录
        
        // 2. 实例化创作类型视图
        let view = ZNWBComposeTypeView.composeTypeView()
        view.delegate = self
        // 3. 显示视图
        view.show()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        delegate = self
        
        setupChildViewControllers()
        
        // 应该在tabBar视图初始化之后添加按钮，防止tabBar将按钮点击事件截获
        tabBar.addSubview(composeButton)
        
        setupUI()
        
        registerNotification()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        let count = CGFloat((viewControllers?.count)!)
        
        // -1 是为了处理tabBarButton之间的容错点问题，增加+按钮的宽度
        let cellWidth = tabBar.bounds.width / count /*- 1: 使用代理方法来解决更规范*/
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * cellWidth, dy: 0)
    }
    
    //覆写计算型属性，让主控制器及其子控制器只支持竖屏(portrait：肖像画 landscape：风景画，横屏)
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}


// MARK: - UITabBarControllerDelegate
extension ZNWBMainController: UITabBarControllerDelegate {
    
    //将要显示某个控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        //两次点击首页，自动滚动到顶部并刷新数据
        let idx = (childViewControllers as NSArray).index(of: viewController)
        
        if selectedIndex == 0 && idx == 0 {
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! ZNWBHomeViewController
            
            vc.tableView?.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
            
            //延时一秒将刷新数据的任务加入到队列中，防止数据刷新导致滚动出现问题
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                vc.loadData()
            }
        }
        
        //isMember是否是该类的对象，不包含子类。isKind表示此类对象，包含子类
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: - 展示撰写微博控制器代理回调
extension ZNWBMainController: ZNWBShowComposeController {
    func presentViewController(clsName: String?) {
        guard let clsName = clsName,
              let vcName = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
        else {
            return
        }
        
        let vc = vcName.init()
        
        // 需要被导航控制器包装才能显示navigationItem
        let nav = UINavigationController(rootViewController: vc)
        
        present(nav, animated: true, completion: nil)
    }
}

extension ZNWBMainController {
    var appVersionKey: String {
        return "appVersion"
    }
    
    var isNewVersion: Bool {
        // 1. 取出当前版本号
        let curVersion = Bundle.main.appVersion
        
        // 2. 取出保存的版本号（保存在用户偏好设置中)
        let preVersion = UserDefaults.standard.object(forKey: appVersionKey) as? String ?? ""
        
        // 3. 将当前版本号存入
        UserDefaults.standard.set(curVersion, forKey: appVersionKey)
        
        // 4. 判断版本号是否一致
        return curVersion != preVersion
    }
    
    fileprivate func setupUI() {
        // 1. 检查版本是否更新
        /*
            主版本号.次版本号.修订版本号
         
            - 主版本号：意味着大的修改，使用者需要适应
            - 次版本号：小的改变，某些函数方法的参数改变
            - 修订版本：程序内部的 bug 修补，完全不影响使用
         */
        
        // 2. 如果是，显示新特性
        let result = isNewVersion ? ZNWBNewFeaturesView.newFeaturesView() : ZNWBWelcomeView.welcomeView()
        
        // 3. 添加视图
        view.addSubview(result)
    }
    
    fileprivate func setupChildViewControllers() {
        //加载沙盒中的应用配置信息，如果没有则加载本地
        let docPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]
        let jsonPath = docPath + "/Preferences/main.json"
        let data = NSData(contentsOfFile: jsonPath)
        
        var messages: [[String: Any]]
        
        if data == nil {
            messages = Bundle.main.appInfo!
        } else {
            guard let result = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as! [[String: Any]]
                else {
                    return
            }
            
            messages = result
        }
        
        //从Bundle中加载应用配置信息
        
        //将所用数组信息生成JSON文件
        //        let data = try! JSONSerialization.data(withJSONObject: messages, options: [.prettyPrinted])
        //        (data as NSData).write(toFile: "/Users/functionmaker/Desktop/main.json", atomically: true)
        
        viewControllers = childViewControllers(messages: messages)
    }
    
    private func childViewControllers(messages: [[String: Any]]) -> [UIViewController] {
        var controllers = [UIViewController]()
        
        for message in messages {
            controllers.append(viewController(message: message))
        }
        
        return controllers
    }
    
    private func viewController(message: [String: Any]) -> UIViewController {
        guard let name = message["className"] as? String,
            let title = message["title"] as? String,
            let imageName = message["imageName"] as? String,
            let className = NSClassFromString(Bundle.main.namespace + "." + name) as? ZNWBBaseViewController.Type,
            let visitorInfo = message["visitorInfo"] as? [String: String]
            else {
                return UIViewController()
        }
        
        let vc = className.init()
        
        vc.title = title
        vc.visitorInfo = visitorInfo
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)

        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .selected)
        
        //default font size is 12 in normal
        //vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: .normal)
        let nav = ZNWBNavigationController(rootViewController: vc)
        
        return nav
    }
}

extension ZNWBMainController {
    fileprivate func registerNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: ZNWBLoginNotification), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(userRegister), name: NSNotification.Name(rawValue: ZNWBRegisterNotification), object: nil)
    }
    
    @objc private func userLogin(noti: Notification) {
        // 说明是在访问过程中token失效
        var when = DispatchTime.now()
        
        if noti.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "自动登录失效，请重新登录")
            
            when = DispatchTime.now() + 2
        }
        
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let nav = UINavigationController(rootViewController: ZNWBOAuthViewController())
            
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    // FIXME: - 未完成注册
    @objc private func userRegister() {
         
    }
}
